//引入定义小仓库的函数
import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
//element-plus提供消息提示组件
import { ElMessage } from 'element-plus'
//引入vue-router里面配置好的路由信息
import { staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'

//引入发请求的函数
import { reqLogin, reqUserInfo, reqLogout } from '@/api/acl/login';
import _ from 'lodash';
import router from '@/router';

//计算出需要动态添加的路由
//参数一：全部动态路由  参数二：用户需要的动态路由
const findUserAsyncRoutes = (allAsyncRoutes: any, routes: any) => {
  return allAsyncRoutes.filter((item: any) => {
    //匹配一级路由
    if (routes.indexOf(item.name) != -1) {
      //匹配二级路由
      if (item.children && item.children.length > 0) {
        item.children = findUserAsyncRoutes(item.children, routes)
      }
      return true;
    }
  })
}

//用户信息
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: [],
    buttonList:[]
  }),

  actions: {
    //登录
    async login(username: string, password: string) {
      try {
        let result = await reqLogin({ username, password })
        //仓库存储token
        this.token = result.token
        //持久化存储
        setToken(result.token)
        return 'ok'
      } catch {
        //登录失败
        return Promise.reject('失败');
      }
    },

    //获取用户信息
    async getInfo() {
      try {
        let result = await reqUserInfo()
        console.log(result)
        //获取用户信息:头像、名字
        this.name = result.name;
        this.avatar = result.avatar;
        this.buttonList = result.buttons;

        //为了解决对比后异步路由数据发生变化，对异步路由列表进行深拷贝
        //计算出用户所需的异步路由
        let userRegisterAsyncRoute = findUserAsyncRoutes(_.cloneDeep(allAsyncRoutes), result.routes);
        //调用方法：动态添加用户注异步路由 + 任意路由
        this.setRoute([...userRegisterAsyncRoute, anyRoute]);
        //左侧导航区域的菜单需要展示的数据
        this.menuRoutes = [...staticRoutes, ...userRegisterAsyncRoute]
        return 'ok'
      } catch (error) {
        return Promise.reject(error);
      }
    },

    //动态添加路由
    setRoute(registerRoute: any) {
      //用户A:B:C：最终需要动态追加的路由
      registerRoute.forEach((item: any) => {
        router.addRoute(item);
      })
    },

    //退出登录
    reset() {
      // 删除local中保存的token
      removeToken()
      // 提交重置用户信息的mutation
      this.token = ''
      this.name = ''
      this.avatar = ''
      //退出前清空路由
      this.resetRoute();
    },

    //重置路由
    resetRoute() {
      //获取当前用户全部路由信息
      let allRoutes = router.getRoutes();
      //退出时清除路由信息
      allRoutes.forEach((item) => {
        //删除路由
        router.removeRoute(item.name)
      });
      //常量路由:动态添加上
      staticRoutes.forEach((item: any) => {
        router.addRoute(item);
      });
  },
  }
});
